package com.xtkj.superclub_friendscircle.interceptor;

import com.xtkj.commons.TokenUtil;
import com.xtkj.superclub_friendscircle.annotation.Login;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 项目名称：superclub
 * 类 名 称：TokenInterceptor
 * 类 描 述：令牌验证是否正确，超时
 * 创建时间：2020/1/4 15:08
 * 创 建 人：xiezhiyan
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Login annotation;
        // 如果处理对象是一个处理方法，则获取到方法上的注解
        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod)handler).getMethodAnnotation(Login.class);
            // 否则直接放过拦截的请求
        } else {
            return true;
        }
        // 说明此方法没有Login注解
        if (annotation == null) {
            return true;
        }
        // 从请求头获取token
        response.setCharacterEncoding("utf-8");
        String token = request.getHeader("token");
        // 如果请求头没有token,则从请求参数中取
        if (StringUtils.isBlank(token)) {
            token = request.getParameter("token");
        }
        System.out.println(token+"=========");
        if (token != null) {
            boolean result = TokenUtil.verify(token);
            System.out.println(result);
            if(result){
                return true;
            }
            System.out.println("非法访问");
            response.getWriter().write("306");
        }
        System.out.println("认证失败");
        response.getWriter().write("50000");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}